package com.studyv3.test.controller.stock;

import com.alibaba.druid.sql.ast.statement.SQLIfStatement;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.studyv3.common.core.domain.PageBean;
import com.studyv3.common.core.domain.R;
import com.studyv3.test.domain.ApplyProduct;
import com.studyv3.test.domain.Batch;
import com.studyv3.test.domain.vo.EchartVo;
import com.studyv3.test.mapper.BatchMapper;
import com.studyv3.test.redis.RedisKeyConfig;
import com.studyv3.test.service.BatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/batch")
public class BatchController {
    @Autowired
    private BatchService batchService;

    @Autowired
    private BatchMapper batchMapper;

//    @Autowired
//    private  RedisTemplate redisTemplate;
    //增
    @PostMapping
    public R add(@RequestBody Batch add){
        return batchService.add(add);
    }

    //删
    @DeleteMapping("/{ids}")
    public R deleteAll(@PathVariable Integer[] ids){
        batchService.deleteUserByIds(ids);
        return R.ok("删除成功");
    }

    //查所有
    @GetMapping("all")
    public R all(){
        return batchService.queryAll();
    }

    //查可申请
    @GetMapping("useable")
    public R useable(){
        return batchService.findUseableBatch();
    }



    //分页查
    @GetMapping
    public R<PageBean<Batch>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) String a,
            @RequestParam(required = false) String b,
            @RequestParam(required = false) String c
    ){
        System.out.println("传入参数："+a+b+c);
        PageBean<Batch> pb = batchService.list(pageNum,pageSize, a, b, c);
        return R.ok(pb);
    }

    @GetMapping("/warehous")
    public R<PageBean<Batch>> listwarehous(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) String a,
            @RequestParam(required = false) String b,
            @RequestParam(required = false) String c
    ){
        System.out.println("传入参数："+a+b+c);
        PageBean<Batch> pb = batchService.listwarehous(pageNum,pageSize, a, b, c);
        return R.ok(pb);
    }

    //改
    @PutMapping
    public R update(@RequestBody Batch batch) {
        return batchService.update(batch);
    }



    //导出
    @PostMapping("export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("商品列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition","attachment;filename="+System.currentTimeMillis()+fileName+".xlsx");
        List<Batch> batches = batchMapper.selectList(null);
        EasyExcel.write(response.getOutputStream(),Batch.class).sheet().doWrite(batches);
    }

    //导入
    @PostMapping("/import")
    public R upload(@RequestPart MultipartFile file) throws IOException {
        if (!file.isEmpty()){
            EasyExcel.read(file.getInputStream(), Batch.class, new ReadListener<Batch>() {
                List<Batch> cachedDataList =new ArrayList<>(1000);

                @Override
                public void invoke(Batch add, AnalysisContext analysisContext) {
                    cachedDataList.add(add);
                    if (cachedDataList.size() >= 1000){
                        //向数据库中存一次数据
                        batchMapper.batchInsert(cachedDataList);
                        //存储完成清理list
                        cachedDataList =new ArrayList<>(1000);
                    }
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    if (cachedDataList.size()>0){
                        batchMapper.batchInsert(cachedDataList);
                    }
                }
            }).sheet().doReadSync();
            return R.ok();
        }
        return R.fail("异常");
    }

    /**
     * 获取所有未审核采购申请
     * @param id
     */
    @GetMapping("/todo")
    public List<ApplyProduct> todoList(Integer id){
        return batchService.todoList(id);
    }

    /**
     * 获取所有已审核采购申请
     * @param id
     */
    @GetMapping("/done")
    public List<ApplyProduct>  doneList(Integer id){
        return batchService.doneList(id);
    }

    @PutMapping("/changeIO")
    public R change( Integer id)  {
        System.out.println("aaaa"+id);
        batchMapper.change(id);
        return R.ok();
    }

    @GetMapping("/elist")
    public List<EchartVo>  elist(){
//        if(redisTemplate.hasKey(RedisKeyConfig.CACHE_TYPES)){
//            return redisTemplate.opsForHash().values(RedisKeyConfig.CACHE_TYPES);}
//        else{
            return batchMapper.elist();
//            Map<String,EchartVo> map=new HashMap<>();
//            elist.forEach(c->{
//                map.put(c.getBname(),c);
//            });
//            redisTemplate.opsForHash().putAll(RedisKeyConfig.CACHE_TYPES,map);
//            return elist;
        }
//    }

}
